﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Threading;
using System.Windows.Controls;
using System.IO;

namespace CnmViewer
{
    static class MyExtensions
    {
        public static void Invoke(this FrameworkElement e, Action a)
        {
            if (e.CheckAccess() == false)
                e.Dispatcher.BeginInvoke(DispatcherPriority.Normal, a);
            else
                a();
        }

        public static bool EqualsIgnoreCase(this string s, string value)
        {
            if (s == null)
                throw new ArgumentNullException("s");

            return s.Equals(value, StringComparison.CurrentCultureIgnoreCase);
        }

        public static void NavigateToStreamOrBlank(this WebBrowser w, Stream s)
        {
            if (s != null)
            {
                if (s.CanSeek)
                    s.Position = 0;
                
                w.NavigateToStream(s);
            }
            else
                w.Navigate(new Uri("about:blank"));
        }

        public static class Tools
        {
            public static string[] GetCmdArgumentsOnly()
            {
                string[] args = GetCmdArguments();

                string[] result = new string[args.Length - 1];
                Array.Copy(args, 1, result, 0, result.Length);

                return result;
            }

            public static string[] GetCmdArguments()
            {
                string args = Environment.CommandLine;

                List<string> result = new List<string>();
                StringBuilder buffer = new StringBuilder();
                char SYM_GROUP = '"';
                char SYM_SPLIT = ' ';

                bool inside = false;
                foreach (char c in args)
                {
                    if (c == SYM_GROUP)
                    {
                        inside = !inside;
                    }
                    else if (c == SYM_SPLIT && inside == false && buffer.Length > 0)
                    {
                        result.Add(buffer.ToString());
                        buffer.Length = 0;
                    }
                    else
                        buffer.Append(c);
                }
                if (buffer.Length > 0)
                    result.Add(buffer.ToString());

                return result.ToArray();
            }
        }
    }
}
